<?php

namespace app\middleware;

use app\common\ApiStatus;
use app\common\OsType;
use app\model\SystemAdmin;
use app\model\User;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class ApiBaseRequest implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $request->header('accept', 'application/json, text/plain, */*');

        if ($request->api_method == 'post') {
            $uuid = $request->post('uuid', '');
            if (empty($uuid)) return json(['code' => ApiStatus::API_NEED_LOGIN->value, 'msg' => 'empty uuid']);
            if (strlen($uuid) < 32) return json(['code' => ApiStatus::API_NEED_LOGIN->value, 'msg' => 'invalid uuid']);
            $request->uuid = $uuid;
            $osType        = $request->post('os_type', 0);
            $adminOsType   = $request->post('admin_os_type', 0); // 后台接口
            if ($adminOsType) $osType = $adminOsType;
            if (empty($osType)) return json(['code' => ApiStatus::API_NEED_LOGIN->value, 'msg' => 'empty os_type']);
            $osType      = intval($osType);
            $osTypeArray = OsType::values();
            if (!isset($osTypeArray[$osType])) return json(['code' => ApiStatus::API_NEED_LOGIN->value, 'msg' => 'invalid os_type']);
            $request->os_type = $osType;
        }

        if (empty(request()->uid)) {
            $uid   = 0;
            $token = $request->header('Authorization', '');
            if (!is_string($token)) $token = '';
            if ($token) {
                $request->token = $token;
                list(, $uid) = User::parseToken($token);
            }
            request()->uid = intval($uid);
        }

        if (empty($request->admin_uid)) {
            $admin_uid  = 0;
            $adminToken = $request->header('Authorization-admin', '');
            if (!is_string($adminToken)) $adminToken = '';
            if ($adminToken) {
                $request->admin_token = $adminToken;
                list(, $admin_uid) = SystemAdmin::adminParseToken($adminToken);
            }
            $request->admin_uid = intval($admin_uid);
        }
        return $next($request);
    }
}